package cn.fboost.mtos.service.impl;

import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.request.SystemConfigUpdateRequest;
import cn.fboost.mtos.service.SystemService;
import cn.fboost.mtos.util.ConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SystemServiceImpl implements SystemService {
    private final ConfigUtil configUtil;

    public SystemServiceImpl(ConfigUtil configUtil) {
        this.configUtil = configUtil;
    }

    @Override
    public Response getConfig(String key) {
        return Response.builder().success()
                .msg("获取成功")
                .data(configUtil.getString(key))
                .build();
    }

    @Override
    public Response getConfigByPrefix(String prefix) {
        if (prefix.endsWith(".")) {
            prefix = prefix.substring(0, prefix.length() - 1);
        }

        return Response.builder().success()
                .msg("获取成功")
                .data(configUtil.getPrefixConfig(prefix))
                .build();
    }

    @Override
    public Response updateConfig(SystemConfigUpdateRequest[] request) {
        for (SystemConfigUpdateRequest updateRequest : request) {
            String[] fields = updateRequest.getKey().split("\\.");
            int len = fields.length - 1;
            for (int i = 0; i < len; i++) {
                StringBuilder prefix = new StringBuilder();
                for (int j = 0; j <= i; j++) {
                    prefix.append(fields[j]).append(".");
                }

                configUtil.clearPrefixConfig(prefix.substring(0, prefix.length() - 1));
            }

            configUtil.setConfig(updateRequest.getKey(), updateRequest.getValue());
        }

        return Response.builder().success().msg("更新成功").build();
    }

    @Override
    @CacheEvict(cacheNames = "sys-config", allEntries = true)
    public Response clearConfigCache() {
        return Response.builder().success().msg("缓存已清除").build();
    }
}
